/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.controller;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vacoor.nothing.security.shiro.filter.ForceLogoutFilter;

/**
 */
@Controller
@RequestMapping("/sessions")
public class ShiroSessionController {

    @Autowired
    private DefaultSessionManager sessionManager;

    @RequestMapping
    public Object list() {
        return sessionManager.getSessionDAO().getActiveSessions();
    }


    @ResponseBody
    @RequestMapping("{sid}/kill")
    public String kill(@PathVariable("sid") String sid) {
        SessionDAO sessionDAO = sessionManager.getSessionDAO();
        Session session = null;
        try {
            session = sessionDAO.readSession(sid);
        } catch (UnknownSessionException ignore) {
            // ignore
        }
        if (session != null) {
            PrincipalCollection principals = (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            Boolean authenticated = (Boolean) session.getAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
            session.setAttribute(ForceLogoutFilter.FORCE_LOGOUT_SESSION_KEY, true);
        }

        return "kill success";
    }

}
